# -*-coding:utf-8-*-

import zipfile
import os

html_files = ['H:\\html\\' + i for i in os.listdir('H:\\html')]

def del_file():
    try:
        os.remove('H:\\剑王朝.epub')
    except PermissionError as e:
        print(e, "文件被占用")
    except FileNotFoundError as e:
        print(e, '没有此文件')
    return 'ok'


def image(epub):
    image = open('H:\\cover.jpg', 'rb').read()
    epub.writestr('images/cover.jpg', image, compress_type=zipfile.ZIP_STORED)
    return 'cover is ok'
# asd = os.listdir('H:\\ttt')


def mimetype(epub):
    epub.writestr('mimetype', 'application/epub+zip',
                  compress_type=zipfile.ZIP_STORED)
    return 'mimetype is ok'


# html_files = ['H:\\title.html', 'H:\\content.html']


def metainf(epub):
    container_xml = '''<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
  <rootfiles>
    <rootfile full-path="OEBPS/Content.opf" media-type="application/oebps-package+xml"/>
  </rootfiles>
</container>'''
    epub.writestr('META-INF/container.xml', container_xml,
                  compress_type=zipfile.ZIP_STORED)
    return 'META-INF is ok'


def make_css(epub):
    css_info = '''body {
  font-family: sans-serif;}
h1, h2, h3, h4 {
  font-family: serif;
  color: red;}'''
    epub.writestr('OEBPS/stylesheet.css', css_info,
                  compress_type=zipfile.ZIP_STORED)
    return 'css is ok'


def write_content(epub):
    manifest = ''''''
    spine = ''''''
    navpoint = ''''''
    for s, htm in enumerate(html_files):
        html = htm[:17] + str(s) + '.xhtml'
        basename = str(s + 1) + '.xhtml'
        manifest = manifest + \
            '\n    <item id="file_%s" href="%s" media-type="application/xhtml+xml"/>' % (
                s, basename)
        spine = spine + '\n    <itemref idref="file_%s"/>' % (s)
        navpoint = navpoint + '''\n    <navPoint id="navpoint-%s" playOrder="%s">
      <navLabel>
        <text>第%s章</text>
      </navLabel>
      <content src="%s"/>
    </navPoint>''' % (s, s, s, basename)
        html_content = open(html, 'r', encoding='utf-8').read()
        epub.writestr('OEBPS/' + basename, html_content,
                      compress_type=zipfile.ZIP_STORED)
    return manifest, spine, navpoint


def opf(manifest, spine, epub):
    index_tpl = '''<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://www.idpf.org/2007/opf"
    xmlns:dc="http://purl.org/dc/element/1.1"
    unique-identifier="bookid" version="2.0">
  <metadata>
    <dc:title>测试</dc:title>
    <dc:creator>Name</dc:creator>
    <dc:identifier id="booid">urn:uuid:12345</dc:identifier>
    <meta name="cover" content="cover-image"/>
  </metadata>
  <manifest>
    <item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>
    <item id="cover" href="images/cover.jpg" media-type="image/jpg"/>
    <iten id="css" href="stylesheet.css" media-type="text/css"/>%(manifest)s
  </manifest>
  <spine toc="ncx">%(spine)s
  </spine>
</package>'''
    epub.writestr('OEBPS/content.opf', index_tpl %
                  {'manifest': manifest, 'spine': spine, }, compress_type=zipfile.ZIP_STORED)
    return 'opf is ok'


def ncx(navpoint, epub):
    init_ncx = '''<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN"
 "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd"><ncx version="2005-1" xmlns="http://www.daisy.org/z3986/2005/ncx/">
  <head>
    <meta content="urn:uuid:12345" name="dtb:uid"/>
    <meta content="0" name="dtb:depth"/>
    <meta content="0" name="dtb:totalPageCount"/>
    <meta content="0" name="dtb:maxPageNumber"/>
  <docTitle>
    <text>测试</text>
  </docTitle>
  <navMap>%s
  </navMap>
</ncx>'''
    epub.writestr('OEBPS/toc.ncx', init_ncx %
                  (navpoint), compress_type=zipfile.ZIP_STORED)
    return 'ncx is ok'

if __name__ == '__main__':
    del_file()
    epub = zipfile.ZipFile('H:\\剑王朝.epub', 'w')
    metainf(epub)
    make_css(epub)
    image(epub)
    manifest, spine, navpoint = write_content(epub)
    opf(manifest, spine, epub)
    ncx(navpoint, epub)
    epub.close()
    print('all is ok')
